using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using HogBlog.Models;

namespace HogBlog.Models
{ 
    public class EntryRepository : IEntryRepository
    {
        HogBlogContext context = new HogBlogContext();

        public IQueryable<Entry> All
        {
            get { return context.Entries; }
        }

        public IQueryable<Entry> AllIncluding(params Expression<Func<Entry, object>>[] includeProperties)
        {
            IQueryable<Entry> query = context.Entries;
            foreach (var includeProperty in includeProperties) {
                query = query.Include(includeProperty);
            }
            return query;
        }

        public Entry Find(int id)
        {
            return context.Entries.Find(id);
        }

        public void InsertOrUpdate(Entry entry)
        {
            if (entry.EntryId == default(int)) {
                // New entity
                context.Entries.Add(entry);
            } else {
                // Existing entity
                context.Entry(entry).State = EntityState.Modified;
            }
        }

        public void Delete(int id)
        {
            var entry = context.Entries.Find(id);
            context.Entries.Remove(entry);
        }

        public void Save()
        {
            context.SaveChanges();
        }
    }

    public interface IEntryRepository
    {
        IQueryable<Entry> All { get; }
        IQueryable<Entry> AllIncluding(params Expression<Func<Entry, object>>[] includeProperties);
        Entry Find(int id);
        void InsertOrUpdate(Entry entry);
        void Delete(int id);
        void Save();
    }
}